<template>
  <div class="detail">
    <template v-if="getData">
      <div class="detail_banner">
        <van-swipe @change="onChange" autoplay="3000">
          <van-swipe-item
            v-for="(image, index) in ItemInfo.storeInfo.slider_image"
            :key="index"
          >
            <img v-lazy="image" />
          </van-swipe-item>
          <template #indicator>
            <div class="custom-indicator">
              {{ swiperCurrent + 1 }}/{{
                ItemInfo.storeInfo.slider_image.length
              }}
            </div>
          </template>
        </van-swipe>
      </div>
      <div class="detail_baseinfo">
        <div class="detail_baseinfo_price">
          <span style="color: red">￥</span>
          <span class="normal">{{ ItemInfo.storeInfo.price }}</span>
          <span class="vip">￥{{ ItemInfo.storeInfo.vip_price }}</span>
          <img
            src=""
            class="vip_icon"
            alt=""
          />
        </div>
        <p class="detail_baseinfo_desc">{{ ItemInfo.storeInfo.store_name }}</p>
        <div class="detail_baseinfo_market">
          <span>原价:￥{{ ItemInfo.storeInfo.ot_price }}</span>
          <span
            >库存:{{ ItemInfo.storeInfo.stock
            }}{{ ItemInfo.storeInfo.unit_name }}</span
          >
          <span
            >销量:{{ ItemInfo.storeInfo.fsales
            }}{{ ItemInfo.storeInfo.unit_name }}</span
          >
        </div>
      </div>
      <div
        class="detail_selectSize"
        v-if="ItemInfo.productValue != ''"
        @click="show = !show"
      >
        <div class="specification">
          <span>已选择：</span>
          <span>{{ ParamsFormat }}</span>
        </div>
        <van-icon name="arrow" color="#827a82" size="0.3rem" />
      </div>
      <div class="detail_evaluate" @click="ToEvaluate(ItemInfo.storeInfo.id)">
        <span>用户评价({{ ItemInfo.replyCount }})</span>
        <div class="goodReputation">
          <span>{{ ItemInfo.replyChance }}%</span>
          <span>好评率</span>
          <van-icon name="arrow" color="#827a82" size="0.3rem" />
        </div>
      </div>
      <div class="detail_goodRecommend">
        <div class="goodRecommend_title">
          <img
            src=""
            alt=""
          />
          <span>优品推荐</span>
          <img
            src=""
            alt=""
          />
        </div>
        <div class="goodRecommend_list">
          <van-swipe class="my-swipe" indicator-color="#e93323">
            <van-swipe-item v-for="(list, index) in goodlist" :key="index">
              <CommodityCard
                v-for="item in list"
                :key="item.id"
                :item="item"
              ></CommodityCard>
            </van-swipe-item>
          </van-swipe>
        </div>
      </div>
      <div class="detail_introduce">
        <div class="introduce_title">产品介绍</div>
        <div v-html="ItemInfo.storeInfo.description" @click.prevent></div>
        <div
          v-if="!ItemInfo.storeInfo.description"
          style="
            text-align: center;
            height: 30px;
            line-height: 30px;
            background: white;
            margin-top: 5px;
          "
        >
          暂无产品介绍
        </div>
      </div>
      <div class="detail_productNav">
        <van-goods-action>
          <van-goods-action-icon
            icon="chat-o"
            text="客服"
            color="#ee0a24"
            @click="service"
          />
          <van-goods-action-icon
            icon="cart-o"
            text="购物车"
            to="/cart"
            :badge="count == 0 ? '' : count"
          />
          <van-goods-action-icon
            icon="star"
            text="已收藏"
            color="#ff5000"
            @click="cancelcollect"
            v-if="collect"
          />
          <van-goods-action-icon
            icon="star-o"
            text="收藏"
            color="#ff5000"
            @click="addcollect"
            v-else
          />
          <van-goods-action-button
            type="warning"
            text="加入购物车"
            @click="addCart"
          />
          <van-goods-action-button
            type="danger"
            text="立即购买"
            @click="buyImmediately"
            v-if="!ItemInfo.storeInfo.stock == 0"
          />
          <van-goods-action-button
            color="#bbbbbb"
            text="已售罄"
            @click="buyImmediately"
            v-else
          />
        </van-goods-action>
      </div>
    </template>
    <template v-else>
      <van-loading size="24px">加载中...</van-loading>
    </template>
    <div class="detail_selectModel">
      <van-popup
        v-model="show"
        closeable
        round
        position="bottom"
        v-if="getData"
      >
        <van-card
          :thumb="
            ItemInfo.productAttr.length > 0
              ? ItemInfo.productValue[ParamsFormat].image
              : ItemInfo.storeInfo.image
          "
        >
          <template #title>
            <p class="title">{{ ItemInfo.storeInfo.store_name }}</p>
          </template>
          <template #price>
            <span class="price"
              >￥{{
                ItemInfo.productAttr.length > 0
                  ? ItemInfo.productValue[ParamsFormat].price
                  : ItemInfo.storeInfo.price
              }}</span
            >
            <span class="inventory"
              >库存：{{
                ItemInfo.productAttr.length > 0
                  ? ItemInfo.productValue[ParamsFormat].stock
                  : ItemInfo.storeInfo.stock
              }}</span
            >
          </template>
        </van-card>
        <ul class="params">
          <li v-for="(item, index) in modelData" :key="index">
            <p class="params_title">{{ item.name }}</p>
            <span
              :class="{
                params_size: true,
                params_size_selected:
                  params[item.name] == item.values[index] ? true : false,
              }"
              v-for="(value, index) in item.values"
              :key="index"
              @click="changparams(item.name, value)"
              >{{ value }}</span
            >
          </li>
          <li>
            <p class="params_title">数量</p>
            <van-stepper v-model="value" :max="ItemInfo.storeInfo.stock" />
          </li>
        </ul>
      </van-popup>
    </div>
  </div>
</template>

<script>
import CommodityCard from "@/components/CommodityCard";
import { mapGetters, mapState, mapActions, mapMutations } from "vuex";
export default {
  components: {
    CommodityCard,
  },
  data() {
    return {
      ItemInfo: null,
      swiperCurrent: 0,
      getData: false,
      show: false,
      params: {},
      ParamsFormat: null,
      value: 1,
      collect: false,
      count: null,
    };
  },
  methods: {
    ...mapActions(["getCollectlist"]),
    ...mapMutations(["getCartProduct"]),
    onChange(index) {
      this.swiperCurrent = index;
    },
    ToEvaluate(id) {
      this.$router.push({
        path: "/evaluate_list",
        query: {
          id,
        },
      });
    },
    changparams(key, value) {
      for (var k in this.params) {
        if (k == key) {
          this.params[k] = value;
        }
      }
      this.getParamsFormat();
      this.$forceUpdate();
    },
    getParamsFormat() {
      var result = "";
      for (var k in this.params) {
        result += this.params[k] + ",";
      }
      this.ParamsFormat = result.slice(0, result.length - 1);
    },
    ToggleShow(callBack) {
      if (!this.show) {
        this.show = !this.show;
        return;
      } else {
        callBack();
      }
    },
    addCart() {
      var add = () => {
        if (!this.isLoginInfo) {
          this.$router.push({
            name:'login',
            params:{
              msg:'未登录',
              flag:true,
            }
          });
          return;
        }
        for (var k in this.ItemInfo.productValue) {
          if (k == this.ParamsFormat) {
            this.uniqueId = this.ItemInfo.productValue[k].unique;
          }
        }
        this.axios
          .post("/api/cart/add", {
            cartNum: this.value,
            new: 0,
            productId: this.ItemInfo.storeInfo.id,
            uniqueId:
              this.ItemInfo.productValue instanceof Array ? "" : this.uniqueId,
          })
          .then(() => {
            this.show = false;
            this.$toast("添加成功");
            this.getCount();
          });
      };
      this.ToggleShow(add);
    },
    buyImmediately() {
      var buy = () => {
        if (!this.isLoginInfo) {
          this.$router.push({
            name:'login',
            params:{
              msg:'未登录',
              flag:true,
            }
          });
          return;
        }
        for (var k in this.ItemInfo.productValue) {
          if (k == this.ParamsFormat) {
            this.uniqueId = this.ItemInfo.productValue[k].unique;
          }
        }
        var CurrentId = this.cartlist.findIndex((item) => {
          return item.productInfo.id == this.ItemInfo.storeInfo.id;
        });
        if (CurrentId == -1) {
          this.axios
            .post(`/api/cart/add`, {
              cartNum: this.value,
              new: this.ItemInfo.storeInfo.is_new,
              productId: this.ItemInfo.storeInfo.id,
              uniqueId:
                this.ItemInfo.productValue instanceof Array
                  ? ""
                  : this.uniqueId,
            })
            .then((response) => {
              return response.data.data;
            })
            .then((response) => {
              this.$router.push({
                path: "/order/submit",
                query: {
                  id: response.cartId,
                },
              });
            });
        } else {
          this.axios
            .post(`/api/cart/add`, {
              cartNum: this.value,
              new: this.ItemInfo.storeInfo.is_new,
              productId: this.ItemInfo.storeInfo.id,
              uniqueId:
                this.ItemInfo.productValue instanceof Array
                  ? ""
                  : this.uniqueId,
            })
            .then((response) => {
              var CardId = response.data.data;
              this.axios
                .post("/api/cart/num", {
                  id: this.cartlist[CurrentId].id,
                  number: this.value,
                })
                .then(() => {
                  return CardId;
                })
                .then((response) => {
                  this.$router.push({
                    path: "/order/submit",
                    query: {
                      id: response.cartId,
                    },
                  });
                });
            });
        }
      };
      this.ToggleShow(buy);
    },
    addcollect() {
      if (!this.isLoginInfo) {
          this.$router.push({
            name:'login',
            params:{
              msg:'未登录',
              flag:true,
            }
          });
          return;
      }
      this.axios
        .post("/api/collect/add", {
          category: "product",
          id: this.ItemInfo.storeInfo.id,
        })
        .then((response) => {
          if (response.data.status == 200) {
            this.collect = true;
            this.getCollectlist(this.token);
          } else {
            console.log("失败");
          }
        });
    },
    cancelcollect() {
      this.axios
        .post("/api/collect/del", {
          category: "product",
          id: this.ItemInfo.storeInfo.id,
        })
        .then((response) => {
          if (response.data.status == 200) {
            this.collect = false;
            this.getCollectlist(this.token);
          } else {
            console.log("失败");
          }
        });
    },
    getCount() {
      if (this.isLoginInfo) {
        this.axios.get("/api/cart/count").then((response) => {
          this.count = response.data.data.count;
        });
      }
    },
    service() {
      this.$toast("客服尚未上岗，请稍后咨询！");
    },
  },
  created() {
    this.getCount();
    this.axios
      .get("/api/product/detail/" + this.$route.query.id)
      .then((response) => {
        this.ItemInfo = response.data.data;
        this.getData = true;
      });
    if (this.isLoginInfo) {
      this.axios.get("/api/cart/list").then((response) => {
        this.getCartProduct(response.data.data.valid);
      });
    }
  },
  computed: {
    ...mapGetters(["isCollect", "isLoginInfo"]),
    ...mapState({
      collectlist: (state) => state.data.list.collect,
      token: (state) => state.data.token,
      cartlist: (state) => state.data.cartproduct,
    }),
    goodlist() {
      var result = [];
      for (var i = 0; i < 3; i++) {
        result.push(this.ItemInfo.good_list.slice(6 * i, 6 * (i + 1)));
      }
      return result;
    },
    modelData() {
      var result = {};
      result = this.ItemInfo.productAttr.map((item) => {
        var name = item.attr_name;
        var values = item.attr_values.filter((item) => {
          return item;
        });
        return { name, values };
      });
      return result;
    },
    collectflag() {
      return this.ItemInfo && this.collectlist;
    },
  },
  watch: {
    "$route.query": function () {
      this.getData = false;
      this.params = {};
      this.axios
        .get("/api/product/detail/" + this.$route.query.id)
        .then((response) => {
          this.ItemInfo = response.data.data;
          this.getData = true;
          this.collect = this.collectlist.some((item) => {
            return item.pid == this.ItemInfo.storeInfo.id;
          });
        });
    },
    ItemInfo(n) {
      for (var i = 0; i < n.productAttr.length; i++) {
        this.params[n.productAttr[i].attr_name] =
          n.productAttr[i].attr_values[0];
      }
      this.getParamsFormat();
      this.value = 1;
    },
    collectflag(n) {
      this.collect = n.some((item) => {
        return item.pid == this.ItemInfo.storeInfo.id;
      });
    },
  },
};
</script>

<style lang="less">
.detail {
  width: 100% !important;
  background-color: #f5f5f5;
  padding-bottom: 60px;
  .detail_banner {
    width: 100%;
    height: 375px;
    .van-swipe {
      width: 100%;
      height: 100%;
      .van-swipe__track {
        width: 100%;
        height: 100%;
        .van-swipe-item {
          width: 100%;
          height: 100%;
          img {
            width: 100%;
            height: 100%;
          }
        }
      }
      .custom-indicator {
        position: absolute;
        right: 5px;
        bottom: 5px;
        padding: 2px 5px;
        font-size: 12px;
        background: rgba(0, 0, 0, 0.1);
      }
    }
  }
  .detail_baseinfo {
    width: 100%;
    padding: 10px;
    background-color: #fff;
    .detail_baseinfo_price {
      width: 100%;
      .normal {
        color: red;
        font-size: 22px;
        font-weight: bold;
        margin-right: 8px;
      }
      .vip {
        font-weight: bold;
        font-size: 14px;
      }
      .vip_icon {
        width: 23px;
        height: 10.5px;
        margin-left: 5px;
      }
    }
    .detail_baseinfo_desc {
      margin-top: 5px;
      font-weight: bold;
    }
    .detail_baseinfo_market {
      margin-top: 10px;
      color: #82848f;
      font-size: 12px;
      display: flex;
      justify-content: space-between;
    }
  }
  .detail_selectSize {
    width: 100%;
    height: 40px;
    padding: 0 15px;
    background-color: #fff;
    margin-top: 10px;
    font-size: 14px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .specification {
      span {
        &:nth-child(1) {
          color: #82848f;
        }
      }
    }
  }
  .detail_evaluate {
    width: 100%;
    height: 40px;
    padding: 0 15px;
    background-color: #fff;
    margin-top: 10px;
    font-size: 14px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .goodReputation {
      span {
        &:nth-child(1) {
          color: red;
        }
        &:nth-child(2) {
          color: #82848f;
        }
      }
      .van-icon {
        vertical-align: -3px;
        margin-left: 5px;
      }
    }
  }
  .detail_goodRecommend {
    width: 100%;
    margin-top: 10px;
    background-color: #fff;
    padding: 10px 15px;
    .goodRecommend_title {
      width: 100%;
      display: flex;
      justify-content: center;
      margin-top: 10px;
      span {
        font-size: 14px;
        color: #f2230b;
        margin: 0 10px;
      }
      img {
        width: 15px;
        height: 15px;
      }
    }
    .goodRecommend_list {
      width: 100%;
      margin-top: 15px;
      .my-swipe {
        width: 100%;
        padding-bottom: 20px;
        .van-swipe__track {
          .van-swipe-item {
            width: 100%;
            margin-right: 5px;
            display: flex;
            flex-wrap: wrap;
            .CommodityCard {
              width: calc((100% - 20px) / 3);
              height: 150px;
              margin-bottom: 10px;
              &:nth-child(3n-1) {
                margin-left: 10px;
                margin-right: 10px;
              }
              .desc {
                .price {
                  font-weight: normal;
                }
              }
            }
          }
        }
        .van-swipe__indicators {
          .van-swipe__indicator {
            width: 8px;
            height: 8px;
            background-color: #ebebeb;
          }
        }
      }
    }
  }
  .detail_introduce {
    width: 100%;
    margin-top: 10px;
    .introduce_title {
      width: 100%;
      height: 40px;
      background-color: #fff;
      text-align: center;
      line-height: 40px;
    }
    .attributes-list {
      width: 100%;
      padding: 0 !important;
      &::after {
        content: "";
        display: block;
        overflow: hidden;
        height: 0;
        clear: both;
      }
      li {
        font-size: 14px;
        height: 30px !important;
        width: 100% !important;
        background-color: #fff;
        padding: 0 10px;
        border-bottom: 1px solid #eee;
      }
    }
    .mui-inline-block {
      width: 100% !important;
      height: auto !important;
    }
    #J_AttrUL {
      width: 100%;
      padding-left: 0 !important;
      padding-right: 0 !important;
      &::after {
        content: "";
        display: block;
        overflow: hidden;
        height: 0;
        clear: both;
      }
      li {
        font-size: 14px;
        height: 30px !important;
        width: 100% !important;
        background-color: #fff;
        padding: 0 10px;
        border-bottom: 1px solid #eee;
        margin-top: 0 !important;
        line-height: 30px !important;
      }
    }
    .col-main,
    .tm-clear {
      width: 100% !important;
      .main-wrap {
        width: 100% !important;
        .content,
        .ke-post {
          width: 100% !important;
        }
      }
    }
    > div {
      > p {
        img {
          margin: 0 !important;
        }
      }
    }
    .tm-tableAttr {
      width: 100% !important;
      th,
      td {
        color: black;
        border: 1px solid black !important;
      }
      thead {
        td {
          font-size: 14px;
          padding: 5px 5px 5px 20px !important;
        }
      }
    }
    .content,
    .ke-post {
      width: 100% !important;
    }
    #J_DcBottomRightWrap {
      width: 100% !important;
      .skin-box-bd {
        width: 100% !important;
        div {
          width: 100% !important;
        }
      }
    }
  }
  .van-loading {
    padding-top: 20px;
    text-align: center;
    padding-bottom: 100vh;
  }
  .detail_productNav {
    width: 100%;
    .van-goods-action {
      z-index: 9999;
    }
  }
  .detail_selectModel {
    .van-popup--bottom {
      bottom: 50px;
      padding-bottom: 20px;
      .van-card {
        .van-card__header {
          .van-card__content {
            .title {
              font-size: 16px;
              width: 80%;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              margin-top: 10px;
            }
            .van-card__bottom {
              margin-bottom: 5px;
              .van-card__price {
                .price {
                  font-size: 16px;
                  color: red;
                  margin-right: 10px;
                }
                .inventory {
                  color: #b5b5b5;
                }
              }
            }
          }
        }
      }
      .params {
        width: 100%;
        padding: 0 15px;
        > li {
          width: 100%;
          &::after {
            content: "";
            display: block;
            height: 0;
            overflow: hidden;
            clear: both;
          }
          .params_title {
            color: #999999;
            margin: 15px 0 10px 0;
          }
          .params_size {
            padding: 3px 10px;
            border-radius: 4px;
            margin-right: 8px;
            border: 1px solid #cfcfcf;
            float: left;
            margin-bottom: 5px;
          }
          .params_size_selected {
            background-color: #ff3700;
            color: white;
            border-color: transparent;
          }
        }
      }
    }
  }
}
</style>